'use server'
import { getServerSession } from "next-auth/next"
import { authOptions } from '@/auth.config'

import { get, post, patch, del } from './fetch'



//* 判断是否是管理员
export async function isAdmin() {
  const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
    return null;
  }
  return session.user.role === 'admin';
}

export async function getCurrentUser() {
  try {
    const session = await getServerSession(authOptions);
    console.log("session", session)
    if (!session?.user?.openid) {
      return null;
    }
    return await get(`/api/v1/users/wx/${session.user.openid}`)
  } catch (error) {
    console.error("Error getting current user:", error);
    return null;
  }
}

export const createUser = async (user) => {
  try {
    console.log("createUser user", user);
    const newUser = await post(`/api/v1/users`, user);
    console.log("createUser newUser", newUser);
    return newUser;
  } catch (error) {
    throw error;
  }
};

export const getUser = async (userId) => {
  try {
    const user = await get(`/api/v1/users/${userId}`)
    return user
  } catch (error) {
    console.error('获取用户失败:', error)
    throw error
  }
}

export const getUserByOpenid = async (openid) => {
  try {
    const user = await get(`/api/v1/users/wx/${openid}`)
    return user
  } catch (error) {
    if (error.message === 'User not found') {
      return null;
    }
    throw error;
  }
}

export const updateUser = async (userId, user) => {
  try {
    const updatedUser = await patch(`/api/v1/users/${userId}`, user)
    return updatedUser
  } catch (error) {
    console.error('更新用户失败:', error)
    throw error
  }
}

export const deleteUser = async (userId) => {
  try {
    const result = await del(`/api/v1/users/${userId}`)
    return result
  } catch (error) {
    console.error('删除用户失败:', error)
    throw error
  }
}

export const getAllUsers = async ({role, status, branch_campus_id}) => {
  try {
    const users = await get(`/api/v1/users`, {role, status, branch_campus_id})
    return users
  } catch (error) {
    console.error('获取用户列表失败:', error)
    throw error
  }
};
